package com.example.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.api.common.Security.JwtConstant;
import com.example.api.common.Security.JwtTokenUtil;
import com.example.api.common.core.CommonResult;
import com.example.api.common.core.HttpStatus;
import com.example.api.dto.LoginRequest;
import com.example.api.entity.Users;
import com.example.api.mapper.UsersMapper;
import com.example.api.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Users findByUsername(String username) {
        return lambdaQuery().eq(Users::getUsername, username).one();
    }

    @Override
    public CommonResult login(LoginRequest request) {
        // 验证用户是否存在
        Users user = findByUsername(request.getUsername());
        if (user == null) {
            return CommonResult.error(HttpStatus.UNAUTHORIZED, "用户不存在");
        }
        // 验证密码是否正确
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            return CommonResult.error(HttpStatus.UNAUTHORIZED, "密码错误");
        }
        // 构建 JWT 负载信息
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtConstant.USER_INFO_ID, user.getUserId());
        claims.put(JwtConstant.USER_INFO_USERNAME, user.getUsername());
        claims.put("role", user.getRole());
        // 生成 JWT token
        String token = JwtTokenUtil.createToken(claims);
        // 构建返回数据
        Map<String, Object> userData = new HashMap<>();
        userData.put("userId", user.getUserId());
        userData.put("username", user.getUsername());
        userData.put("role", user.getRole());
        userData.put("email", user.getEmail());
        return CommonResult.success("登录成功")
                .put("data", userData)
                .put("token", token);
    }




}
